var app = getApp()
var util=require('../../utils/util.js');
var payjs=require('../../utils/pay.js');
Page({
  data: {
    userInfo: '',   
    order:{},
    shopinfo:{},
    imghost: app.globalData.imghost,

    inSubmit:false,
    lefttime:1800,
    evaluate:{},
    diningType:['堂食','自取','外卖'],
    //外卖 是显示地图 
    markers: [],
    polyline: [],
    location:{},

    redpackage:{},

    
  },  
  //获取当前位置
  onLoad: function (options) {    
    var oid = options.oid;
    var orderNo = options.orderNo;
    this.getOrderDetail(oid, orderNo);
    this.getLocation();
    this.setData({
      shopinfo: wx.getStorageSync("shopinfo"),
      userInfo: wx.getStorageSync("weiuser")
    })
  },
  
  getLocation:function(){
    var that = this
    wx.getLocation({
      success: function (res) {
        that.setData({
          hasLocation: true,
          location: {
            longitude: res.longitude,
            latitude: res.latitude
          }
        })
      }
    })
  },

  onShow:function(){
    var order = this.data.order;
    if (order.state!=0){
      return;
    }
    var that = this;
    var red = this.data.redpackage;
    var disamount = this.getRedDisAmount();
    var orderredpackage = { id: red.id,title:red.title,disamount:disamount}
    
    order.orderRedPacket = [orderredpackage];
    this.setData({
      order: order
    })
    
  },
  getOrderDetail: function (oid, orderNo){
    var that=this;
    if (!oid && !orderNo) return ;
    if (!oid) oid=0;
    var url=util.url.order_id+"?oid="+oid +"&orderNo="+orderNo;
    util.fetchGet(
      url,
      function(ret){
        var order=ret.data;
        
        if (order.future==1){
          var fetchTime = order.fetchTime;
          fetchTime = fetchTime.substring(10, fetchTime.length)
          order.fetchTime = fetchTime;
        }else{
          var fetchTime=order.createTime.date;
          fetchTime=util.getNextTime(3, fetchTime);
          fetchTime = fetchTime.substring(10, fetchTime.length)
          order.fetchTime = fetchTime;
        } 
        order.createTimeStr = util.getNextTime(0, order.createTime.date); 
        
        that.setData({
          order: order
        })
        if (order.paystate == 0 && order.state == 0) {
          that.setExperid();
        }
        if (order.evstate == 1) {
          that.getEvaluate(oid);
        }
        if (order.dining==2){
          that.setMapMark();
        }
      }
    )
  },
  
  calling: function () {
    wx.makePhoneCall({
      phoneNumber: '18316588252',
      success: function () {
        console.log("拨打电话成功！")
      },
      fail: function () {
        console.log("拨打电话失败！")
      }
    })
  }, 
  
  
  toEvaluate: function() {
    var order=this.data.order;
    var suborder = order.subOrder;
    var name="";
    for (var j = 0; j < suborder.length; j++) {
      name += suborder[j].name + "+";
    }
    if (name.length > 1) {
      name = name.substring(0, name.length - 1);
    } 
    wx.navigateTo({
      url: '../evaluate/evaluate?oid=' + order.id+"&name="+name,
    })  
  },
  openRedPackage:function(e){
    var order=this.data.order;
    if (order.state!=0 && order.paystate!=0) return ;
    var amount=e.currentTarget.dataset.amount;
    wx.navigateTo({
      url: '../myPackage/myPackage?amount=' + amount +"&shop="+this.data.shopinfo.id,
    })
  },
  cancleOrder:function(e){
    
    var oid = e.currentTarget.dataset.oid;
    this.cancleOrderById()
  },
  cancleOrderById:function(oid){
    var order = this.data.order;
    var url = util.url.order_cancle + "?oid=" + oid;
    if (order.state != 0) {
      util.showinfo("只有未支付的订单可以取消");
      return;
    }
    var that = this;
    util.fetchGet(
      url,
      function (data) {

        order.state = -1;
        that.setData({
          order: order
        })
      }
    )
  },
  payOrder:function(e){
    if (this.data.inSubmit) {
      util.showinfo("请求正在处理中，请稍后");
      return;
    } 
    var order = this.data.order;
    var createTime=order.createTime;
    var time = new Date().getTime();
    if (time-createTime > 1000 * 60 * 30){
      util.showinfo("订单已取消")
      return ;
    }

    this.setData({ inSubmit:true})
    var oid = e.currentTarget.dataset.oid;
    
    if (order.state != 0) {
      util.showinfo("订单不能重复支付");
      return;
    }
    if (order.redpackage.id){
      var url = util.url.order_setredpacket + "?oid=" + oid + "&rid=" + order.redpackage.id;
      util.fetchGet(
        url,
        function (data) {
          payjs.payOrder(oid, function (succ, ret) {
            that.setData({ inSubmit: false })
            if (succ) {
              util.showinfo("支付成功")
            } else {
              util.showinfo("支付失败，请重试")
            }
          })
        }
      ) 
    }else{
      payjs.payOrder(oid, function (succ, ret) {
        that.setData({ inSubmit: false })
        if (succ) {
          util.showinfo("支付成功")
        } else {
          util.showinfo("支付失败，请重试")
        }
      })
    }
       
  },
  anotherOrder: function (e) {
    wx.navigateTo({
      url: '/pages/submitOrder/submitOrder?oid=' + e.currentTarget.dataset.oid,
    })
  },
  confirmOrder:function(e){
    var that=this;
    var oid=e.currentTarget.dataset.oid;
    var url = util.url.order_confirm + "?oid=" + oid;
    util.fetchGet(
      url,
      function (data) {
        var order=that.data.order;
        order.foodstate=2;
        order.state=2
        order.stateName = "已完成"
        that.setData({order:order})
      } 
    )
  },
  setExperid:function(){
    var that=this;
    
    var interval=setInterval(function(){
      var order = that.data.order;
      var time = new Date(order.createTime.date).getTime(); 
      var now = new Date().getTime();
      var left = 1800-((now - time) / 1000);
      var miu = 0, sec = 0;
      var lefttime = "";
      miu = parseInt(left / 60);
      sec = parseInt(left % 60);
      if (miu > 0) {
        lefttime = miu + "分"
      } 
      if (sec > 0) {
        lefttime += sec + "秒"
      }
      //if (lefttime==="") lefttime="0";
      that.setData({
        lefttime: lefttime
      })
      if (lefttime==""){
        that.cancleOrderById(order.id);
        order.state=-1;
        order.stateName = '已取消';
        that.setData({order:order});          
        clearInterval(interval)    ;    
      }
    },1000)
    
  },
  getEvaluate:function(oid){
    var that=this;     
      var url = util.url.user_evaluate_getbyorder + "?oid=" + oid;
      util.fetchGet(
        url,
        function(ret){
          var evaluate = ret.data;
          var stars=[];
          var i=0;
          while (i < evaluate.star){
            stars.push(1);i++
          }
          evaluate.stars = stars;
          that.setData({
            evaluate:ret.data
          })
        }
      )
  },
  setMapMark:function(){
    var order=this.data.order;
    if (order.dining!=2) 
      return ;
    var shopinfo = this.data.shopinfo;
    var imghost=this.data.imghost;
    var shopMark={
      iconPath: imghost + shopinfo.pic,
      id: 0,
      latitude: shopinfo.address.location.y,
      longitude: shopinfo.address.location.x,
      width: 40,
      height: 40
    };
    var userAddress=order.userAddress;
    var userInfo = this.data.userInfo;
    var userMark={ 
      iconPath: userInfo.avatar,
      id: 1,
      latitude: userAddress.address.location.x,
      longitude: userAddress.address.location.y,
      width: 40,
      height: 40
    };
    //当状态处于骑手已接单时，获取骑手的位置
    var qishouMark ={
      iconPath: "../../img/qishou.png",
      id: 2,
      latitude: userAddress.address.location.x+0.02312,
      longitude: userAddress.address.location.y-0.02345,
      width: 40,
      height: 40
    };
    var markers=[]; 
    markers.push(userMark);
    if (order.foodstate == 0 || order.foodstate==1){
      markers.push(shopMark);
    }    
    if (order.foodstate==2){
      markers.push(qishouMark);
    } 
    this.setData({
      markers:markers
    })
    var distance=this.getDistance(userMark.latitude,userMark.longitude,shopMark.latitude,shopMark.longitude);
    console.log(distance);
    this.setData({
      distance:distance
    })
  }, 
  
  getDistance: function (lat1, lng1, lat2, lng2) {
    var radLat1 = lat1 * Math.PI / 180.0;
    var radLat2 = lat2 * Math.PI / 180.0;
    var a = radLat1 - radLat2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
      Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;// EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000;
    return s;
  },

  getRedDisAmount: function () {
    var redpackage = this.data.redpackage;
    if (redpackage) {
      var dis = 0;
      var amount = this.data.order.amount
      if (redpackage.redtype == 0) {
        var discount = redpackage.discount;
        if (discount && discount != 0) {
          dis = (100 - discount) / 100 * amount;
        }
      } else if (redpackage.redtype == 1) {
        var reduction = redpackage.reduction;
        reduction.sort(function (a, b) {
          return b.full - a.full;
        })
        for (var i = reduction.length - 1; i >= 0; i--) {
          if (amount >= reduction[i].full * 100) {
            dis = reduction[i].reduce * 100;
            break;
          }
        }

      }
      dis = dis.toFixed(0);
      return dis;
    }
    return 0;
  },
  onUnload:function(){
    wx.switchTab({
      url: '/pages/order/order',
    })
  }
})